<?php

namespace App\Http\Controllers\Api;

use App\Handlers\ExpressHandler;
use App\Handlers\ImageUploadHandler;
use App\Models\Config;
use App\Models\LogisticsInfo;
use App\Models\User;
use App\Models\UserLabel;
use Illuminate\Http\Request;

/**
 * @title 通用接口
 * @description 接口说明
 */
class CommonController extends ApiController
{

    /**
     * @title 上传图片
     * @description 接口说明：普通上传is_base64=0;base64上传 is_base64=1
     * @author wjx
     * @url /api/upload_img
     * @method post
     *
     * @param name:image type:string require:1 default:1 other: desc:图片
     * @param name:is_base64 type:int require:1 default:1 other: desc:是否是base64图片
     *
     * @return path:图片路径
     */
    public function upload_img(Request $request, ImageUploadHandler $uploader)
    {
        $image = $request->image;

        $is_base64 = $request->is_base64;
        if (!$image || !isset($is_base64)) {
            return $this->failed('缺少参数');
        }

        if ($request->image && $is_base64 == 1) {
            $result = $uploader->saveBase64Image($image, 'common', 1);

            if ($result) {
                return $this->success($result);
            } else {
                return $this->message('图片上传失败');
            }
        } else {
            $this->validate(
                request(),
                [
                    'image' => 'required|mimes:jpeg,bmp,png,gif',
                ],
                [
                    'image.required' => '请选择图片',
                    'image.mimes' => '图片格式错误，请重新选择',
                    // 'avatar.dimensions' => '图片的清晰度不够，宽和高需要 200px 以上',
                ]
            );
            $result = $uploader->save($image, 'common', 2);
            return $this->success($result);
        }
    }


    /**
     * @title 获取标签
     * @description 接口说明
     * @author wjx
     * @url /api/get_labels
     * @header name:accessToken require:1 default: desc:accessToken
     *
     * @method post
     *
     * @return id:标签ID
     * @return name:标签名称
     */
    public function get_labels(UserLabel $user_label)
    {
        $labels = $user_label->where('is_show', 1)->get();
        $labels->transform(function ($label) {
            return $label->only(['id', 'name']);
        });
        return $this->success($labels);
    }
    /**
     * @title 生成图片验证码
     * @description 接口说明
     * @author wjx
     * @url /api/get_image_code
     * @method POST
     * @return key:验证key
     * @return img:base64图片
     */
    public function get_image_code()
    {
        $captcha = app('captcha')->create('default', true);
        $image = explode(',', $captcha['img']);
        $captcha['img'] = $image[1];
        return $this->success($captcha);
    }
    /**
     * @title 发送短信验证码(通用)
     * @description 接口说明:需要登录，但不需要图片验证码
     * @author wjx
     * @url /api/sendByToken
     * @header name:accessToken require:1 default: desc:accessToken     
     * @method post
     *
     * @param name:phone type:string require:1 default:1 other: desc:手机号
     *
     */
    public function sendByToken(Request $request)
    {
        $this->validate(
            request(),
            [
                'phone' => 'required|regex:/^1[34578][0-9]{9}$/',
            ],
            [
                'phone.required' => '请输入手机号',
                'phone.regex' => '手机号格式不正确',
            ]
        );
        $phone = $request->phone;
        $result = sendCodeAndSave($phone);

        if ($result['success']) {
            return $this->message($result['message']);
        } else {
            return $this->failed($result['message']);
        }
    }
    /**
     * @title 发送短信验证码(特殊)
     * @description 接口说明:需要图片验证码,但不需要登录
     * @author wjx
     * @url /api/sendByGraph
     *     
     * @method post
     *
     * @param name:phone type:string require:1 default: other: desc:手机号
     * @param name:key type:string require:1 default: other: desc:验证key
     * @param name:captcha type:string require:1 default: other: desc:图片验证码
     *
     */
    public function sendByGraph(Request $request)
    {
        $this->validate(
            request(),
            [
                'captcha' => 'required|captcha_api:' . $request->key,
            ],
            [
                'captcha.required' => '请输入图片验证码',
                'captcha.captcha_api' => '验证码错误',
            ]
        );
        $phone = $request->phone;

        $result = sendCodeAndSave($phone);

        if ($result['success']) {
            return $this->message($result['message']);
        } else {
            return $this->failed($result['message']);
        }
    }

    /**
     * @title 发送短信验证码(注册)
     * @description 接口说明:需要图片验证码,但不需要登录
     * @author wjx
     * @url /api/sendByRegister
     *     
     * @method post
     *
     * @param name:phone type:string require:1 default: other: desc:手机号
     * @param name:key type:string require:1 default: other: desc:验证key
     * @param name:captcha type:string require:1 default: other: desc:图片验证码
     *
     */
    public function sendByRegister(Request $request)
    {
        $this->validate(
            request(),
            [
                'captcha' => 'required|captcha_api:' . $request->key,
            ],
            [
                'captcha.required' => '请输入图片验证码',
                'captcha.captcha_api' => '验证码错误',
            ]
        );
        $phone = $request->phone;
        $has_user = User::where('phone',$phone)->first();
        if($has_user){
            return $this->failed('该手机号已注册,请直接登录');
        }
        $result = sendCodeAndSave($phone);

        if ($result['success']) {
            return $this->message($result['message']);
        } else {
            return $this->failed($result['message']);
        }
    }

    /**
     * @title 查询物流信息
     * @description 接口说明
     * @author wjx
     * @url /api/getExpressInfo
     * @header name:accessToken require:1 default: desc:accessToken     * 
     * @method post
     *
     * @param name:com_no type:string require:1 default:1 other: desc:物流公司编号
     * @param name:logistics_no type:string require:1 default:1 other: desc:物流订单号
     */
    public function getExpressInfo(Request $request, ExpressHandler $express)
    {
        $com_no = $request->com_no;
        $logistics_no = $request->logistics_no;

        if (!$com_no || !$logistics_no) {
            return $this->failed('缺少参数');
        }
        if ($request->com_no === 'sf') {
            $info = LogisticsInfo::where(['com_no' => 'sf', 'logistics_no' => $logistics_no])->with('userAddr')->first();
            if(!$info){
                return $this->failed('单号错误');
            }
            $phone = $info->userAddr->phone;
            $receiverPhone = substr($phone, 7, 11);
        }else{
            $receiverPhone = 0;
        }

        $result = $express->query($com_no, $logistics_no, $receiverPhone); //执行查询

        if ($result['error_code'] == 0) { //查询成功
            $list = $result['result']['list'];
            
            return $this->success($list);
        } else {
            return $this->failed($result['reason']);
        }
    }
    /**
     * @title 分享链接
     * @description 接口说明
     * @author wjx
     * @url /api/shareUrl
     * @method post
     * @header name:accessToken require:1 default: desc:用户token
     */
    public function shareUrl(Request $request)
    {
        $user = $request->user;
        $url = config('app.url') . "/register/" . $user->code;
        return $this->success($url);
    }
    /**
     * @title IOS审核
     * @description 接口说明
     * @author wjx
     * @url /api/iosCode
     * @method post
     */
    public function iosCode(Request $request)
    {
        $code = Config::where('name', 'IOS_CODE')->value('value');
        $status = Config::where('name', 'IOS_STATUS')->value('value');

        return response()->json(compact('code', 'status'));
    }
    /**
     * @title 线上店铺地址
     * @description 接口说明
     * @author wjx
     * @url /api/onlineShopUrl
     * @method post
     */
    public function onlineShopUrl(Request $request)
    {
        $onlineShopUrl = "http://47.52.163.68/#/";

        return $this->success(compact('onlineShopUrl'));
    }

    /**
     * @title APP版本更新
     * @description 接口说明
     * @author wjx
     * @url /api/appUpdate
     * @method post
     * @param name:version type:string require:1 default: other: desc:当前版本号
     * 
     * @return update:yes/no
     * @return new_version:新版本号
     * @return apk_file_url:下载链接
     * @return update_log:更新信息
     * @return constraint:是否强制更新0否1是
     */
    public function appUpdate(Request $request)
    {
        $version = $request->version;
        if(!$version){
            return $this->failed('缺少参数version');
        }
        $now_version = Config::where('name','APP_VERSION')->value('value');
        
        if($version === substr($now_version,1,5)){
            return $this->success(['update'=>'no']);
        }else{
            $info = [];
            $info['update'] = 'yes';
            $info['new_version'] = $now_version;
            $info['apk_file_url'] = asset('storage/apk/Eclothes_V1.0.0_20190826.apk');
            $info['update_log'] = '修复若干bug';
            $info['constraint'] = 1;
            return $this->success($info);
        }
        
    }
    /**
     * @title 客服链接
     * @description 接口说明
     * @author wjx
     * @url /api/customer
     * @method post
     * @header name:accessToken require:1 default: desc:用户token 
     *
     * @return customer_url:跳转链接
     */
    public function customer(Request $request)
    {
        $user = $request->user;
        $data = json_encode([
            'nickname' => $user->nickname,
            'mobile' => $user->phone,
            'avatar' => $user->avatar,
        ]);
        $customer_url = "https://chat.xiankefu.com/?bid=2eb0b523145a01089a00bdfbb29e8604&csid=cef2c412ad0c09d4473aa90c2e95e8eb&pageType=mobile&data=".urlencode($data);

        
        return $this->success(compact('customer_url'));
    }

}
